package com.cloudweb.oa.service;

import cn.js.fan.security.SecurityUtil;
import cn.js.fan.security.ThreeDesUtil;
import cn.js.fan.util.DateUtil;
import cn.js.fan.util.ErrMsgException;
import cn.js.fan.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.cache.DepartmentCache;
import com.cloudweb.oa.cache.DeptUserCache;
import com.cloudweb.oa.cache.UserCache;
import com.cloudweb.oa.config.JwtProperties;
import com.cloudweb.oa.entity.Department;
import com.cloudweb.oa.entity.User;
import com.cloudweb.oa.exception.ValidateException;
import com.cloudweb.oa.security.AuthUtil;
import com.cloudweb.oa.utils.ConstUtil;
import com.cloudweb.oa.utils.JwtUtil;
import com.cloudweb.oa.utils.SysProperties;
import com.cloudweb.oa.utils.SysUtil;
import com.cloudweb.oa.vo.Result;
import com.cloudweb.oa.vo.UserVO;
import com.cloudwebsoft.framework.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Service
public class SsoService {

    @Autowired
    HttpServletRequest request;

    @Autowired
    SysUtil sysUtil;

    @Autowired
    AuthUtil authUtil;

    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    JwtProperties jwtProperties;

    @Autowired
    SysProperties sysProperties;

    @Autowired
    UserCache userCache;

    @Autowired
    IUserService userService;

    @Autowired
    IDepartmentService departmentService;

    @Autowired
    IDeptUserService deptUserService;

    @Autowired
    DepartmentCache departmentCache;

    @Autowired
    DeptUserCache deptUserCache;

    public String syncOrg(String info) throws ErrMsgException {
        com.redmoon.oa.sso.Config ssoCfg = new com.redmoon.oa.sso.Config();
        info = ThreeDesUtil.decrypthexstr(ssoCfg.getKey(), info);
        String[] ary = StrUtil.split(info, "\\|");
        if (ary==null) {
            throw new ErrMsgException("操作非法");
        }

        if (ary.length < 6) {
            throw new ErrMsgException("格式非法");
        }

        String timestamp = ary[5];
        Date d = DateUtil.parse(timestamp);
        // 大于 30 秒则超时
        if ((d.getTime() - (new Date()).getTime())/1000 > 30) {
            throw new ErrMsgException("超时\"");
        }

        String userName = ary[0];
        // 帐户
        String account = ary[1];
        String realName = ary[2];
        String deptCode = ary[3];
        String deptName = ary[4];
        String meta = "";
        if (ary.length > 6) {
            meta = ary[6];
        }
        String unitCode = "";

        String[] aryDeptCode = deptCode.split("\\\\");
        String[] aryDeptName = deptName.split("\\\\");
        if (aryDeptCode.length != aryDeptName.length) {
            throw new ErrMsgException("部门格式非法");
        }

        int layer = 2;
        Department parentDept = null;
        for (int i=0; i<aryDeptCode.length; i++) {
            Department department = departmentCache.getDepartment(aryDeptCode[i]);
            if (department == null) {
                department.setCode(aryDeptCode[i]);
                department.setName(aryDeptName[i]);
                department.setLayer(layer);
                if (parentDept == null) {
                    department.setParentCode(ConstUtil.DEPT_ROOT);
                } else {
                    department.setParentCode(parentDept.getCode());
                }
                try {
                    departmentService.create(department);
                } catch (ValidateException e) {
                    LogUtil.getLog(getClass()).error(e);
                    throw new ErrMsgException(e.getMessage());
                }
            }
            parentDept = department;
            layer ++;
        }

        User user = userCache.getUser(userName);
        if (user == null) {
            // 创建用户
            user = new User();
            UserVO userVO = new UserVO();
            try {
                String mobile = "";

                userVO.setName(userName);
                userVO.setRealName(realName);

                com.redmoon.oa.security.Config scfg = com.redmoon.oa.security.Config.getInstance();
                // 默认密码
                String defaultPwd = scfg.getInitPassword();
                userVO.setPwdRaw(defaultPwd);
                String pwdMD5 = "";
                try {
                    pwdMD5 = SecurityUtil.MD5(defaultPwd);
                } catch (Exception e) {
                    LogUtil.getLog(getClass()).error(e.getMessage());
                    throw new ErrMsgException(e.getMessage());
                }
                userVO.setPwd(pwdMD5);
                userVO.setMobile(mobile);
                userVO.setUnitCode(unitCode);
                userVO.setIsPass(1);
                userVO.setLoginName(account);

                userService.create(userVO, false);
            } catch (IOException | ErrMsgException e) {
                LogUtil.getLog(getClass()).error(e);
                throw new ErrMsgException(e.getMessage());
            }
        }

        authUtil.doLoginByUserName(request, userName);
        // 生成token
        return jwtUtil.generate(userName);
    }

}
